from flask import Blueprint, redirect, render_template, request
from sqlalchemy import or_

from app.database.models import Message
from app.server.flask_app import db, http_auth

main_bp = Blueprint(
    "main_bp", __name__, template_folder="templates", static_folder="static"
)


@main_bp.route("/messages", methods=["GET", "POST"])
@http_auth.required
def messages():
    page = request.args.get("page", 1, type=int)
    allMessages = Message.query.filter(
        or_(Message.answer == None, Message.answer == "")
    ).paginate(page=page, per_page=10)

    return render_template("messages/index.html", allMessages=allMessages)


@main_bp.route("/update/<int:id>", methods=["GET", "POST"])
@http_auth.required
def update(id):
    if request.method == "POST":
        message_answer = request.form["answer"]

        message = Message.query.filter_by(id=id).first()
        message.answer = message_answer

        db.session.add(message)
        db.session.commit()
        return redirect("/messages")

    message = Message.query.filter_by(id=id).first()

    return render_template("messages/update.html", message=message)
